<template>
  <view class="category-products">
    <view class="p-4 bg-white shadow-md">
      <text class="text-xl font-bold">{{ categoryName }}</text>
    </view>
    <scroll-view scroll-y class="h-full">
      <view class="p-4 grid grid-cols-2 gap-4">
        <view v-for="product in products" :key="product.id" 
              class="bg-white rounded-lg shadow overflow-hidden"
              @click="navigateToDetail(product)">
          <image :src="product.image" mode="aspectFill" class="w-full h-32 object-cover"/>
          <view class="p-2">
            <text class="text-sm font-medium">{{ product.name }}</text>
            <view class="mt-1 flex justify-between items-center">
              <text class="text-red-500 font-bold">¥{{ product.price }}</text>
              <u-button size="mini" type="primary" @click.stop="addToCart(product)">加入购物车</u-button>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getCategoryProducts, CategoryProduct } from '@/api/shop';

const categoryName = ref('');
const products = ref<CategoryProduct[]>([]);

const navigateToDetail = (product: CategoryProduct) => {
  uni.navigateTo({
    url: '/pages/shop/product_detail',
    success: (res) => {
      res.eventChannel.emit('productData', product);
    }
  });
};

const addToCart = (product: CategoryProduct) => {
  console.log('Adding to cart:', product);
  uni.showToast({
    title: '已加入购物车',
    icon: 'success'
  });
};

onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const { categoryId, name } = currentPage.$page?.options || {};

  categoryName.value = name || '���品分类';

  if (categoryId) {
    getCategoryProducts(Number(categoryId)).then(data => {
      products.value = data;
    }).catch(error => {
      console.error('Failed to fetch category products:', error);
    });
  }
});
</script>